import Vue from 'vue'
import App from './App'
import uView from "uview-ui";
Vue.use(uView);

Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
  ...App
})
/**
 * 注入全局过滤器
 */
import GlobalFilter from "@/common/filter";
Vue.use(GlobalFilter);
//引入拦截器
import httpInterceptor from '@/common/http.interceptor.js'
Vue.use(httpInterceptor, app)
//绑定api接口
import httpApi from '@/common/http.api.js'
Vue.use(httpApi, app)
// 引入uView对小程序分享的mixin封装
let mpShare = require('uview-ui/libs/mixin/mpShare.js');
Vue.mixin(mpShare)
// /**
//  * 导入微信jssdk
//  */
// import jwx from '@/common/jwx'
// Vue.prototype.$jwx = jwx

let isAuthRedirecting = false; // 标志位，避免重复跳转

// 在 main.js 中添加全局配置
uni.addInterceptor('request', {
	invoke(args) {
		// 在请求之前做的事情，比如添加统一 token
		args.header = {
			...args.header,
			Authorization: uni.getStorageSync('token') || ''
		};
		return args;
	},
	success(response) {
		// 统一处理未授权状态
		if (response.statusCode === 401) {
			let page = getCurrentPages()
			uni.setStorageSync("firstPage", page[0].route);
			uni.setStorageSync("options", page[0].options);
			if (!isAuthRedirecting) {
				isAuthRedirecting = true; // 设置标志位
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/auth/login', // 跳转到授权页面
						complete() {
							isAuthRedirecting = false; // 重置标志位
						}
					});
				}, 500);
				return Promise.reject('Unauthorized'); // 确保 reject 请求，不影响后续流程
			}
		}
		return response;
	},
	fail(error) {
		console.log('请求失败', error);
		return Promise.reject(error);
	}
});

app.$mount()